/**   
 * @Title: ChildJobTimerIStempImpl.java 
 * @Package cn.com.commons.quartzframe.job 
 * @Description: 执行子任务的执行器实现
 * @author chenmin-ds   
 * @version V1.0   
 */

package cn.com.klun.job;


import cn.com.klun.cache.QuartzTaskConfigCache;
import cn.com.klun.cache.TaskThreadCache;
import cn.com.klun.factory.SpringBeanFactory;
import cn.com.klun.inter.ITask;
import net.sf.json.JSONObject;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @ClassName: ChildJobTimerIStempImpl
 * @Description: 执行子任务的执行器实现
 * @author chenmin-ds
 */
public class ChildJobTimerIStempImpl implements Job {

	private Logger logger = LoggerFactory.getLogger("ChildJobTimerIStempImpl");

	/*
	 * (非 Javadoc) <p>Title: execute</p> <p>Description: </p>
	 * 
	 * @param context
	 * 
	 * @throws JobExecutionException
	 * 
	 * @see org.quartz.Job#execute(org.quartz.JobExecutionContext)
	 */
	@Override
    @SuppressWarnings({ "rawtypes", "unchecked" })
	public void execute(JobExecutionContext context) throws JobExecutionException {
		JSONObject obj = (JSONObject) context.getJobDetail().getJobDataMap().get("TaskBasicConfig");
		try {
			String taskId = context.getJobDetail().getKey().getName();
			
			if(!TaskThreadCache.getTaskCount(obj.getString("taskNo"),obj.getInt("onetaskLimitCount"))){
				logger.info("任务线程数超过并发最大上限数，任务名称【{}】，任务对象名称【{}】，任务上限数【{}】",obj.getString("taskName"),obj.getString("onetaskLimitCount"));
				return ;
			}
			
			Object objIStep = SpringBeanFactory.getBean(obj.getString("businessObjName").trim());
			logger.info("并行普通" + objIStep.toString());
			if(null == objIStep){
				logger.info("没有找到可执行的任务对象，任务名称【{}】，任务对象名称【{}】" , obj.getString("taskName"),obj.getString("businessInfo"));
			}else{
				ITask istep = (ITask) objIStep;
				List<Object> list = istep.queryTaskInfo(obj);
				if (list != null) {
					for (Object temp : list) {
						istep.runTask(temp);
					}
					istep.editTaskInfo(list);
					QuartzTaskConfigCache.setTaskRunLogCount(taskId, list.size());
					list.clear();
				} else {
					QuartzTaskConfigCache.setTaskRunLogCount(taskId, 0);
					logger.info("没有查询到需要执行的记录，任务对象名称【{}】，任务参数【{}】" , obj.getString("taskName"), obj.getString("businessInfo"));
				}
			}
			TaskThreadCache.setTaskCount(obj.getString("taskNo"));
		} catch (Exception e) {
			logger.error("任务执行异常：" + obj.getString("taskNo"), e);
			TaskThreadCache.setTaskCount(obj.getString("taskNo"));
		}
	}

}
